package com.bawei.flink.demo;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.typeinfo.BasicTypeInfo;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.KeyedBroadcastProcessFunction;
import org.apache.flink.util.Collector;
import scala.Int;

import java.util.Map;
import java.util.Random;

public class BroadCastDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(2);
        DataStreamSource<String> ruleLines = env.socketTextStream("cdh1", 9998);

        MapStateDescriptor<String, Rule> rulesBroadcastState = new MapStateDescriptor<>(
                "RulesBroadcastState",
                BasicTypeInfo.STRING_TYPE_INFO,
                TypeInformation.of(new TypeHint<Rule>() {})
        );

        SingleOutputStreamOperator<Rule> maped = ruleLines.map(new MapFunction<String, Rule>() {
            @Override
            public Rule map(String value) throws Exception {
                String[] arr = value.split(",");
                return new Rule(arr[0],arr[1]);
            }
        });

        BroadcastStream<Rule> broadcast = maped.broadcast(rulesBroadcastState);


        DataStreamSource<String> lines = env.socketTextStream("cdh1", 9999);
        lines.flatMap(new FlatMapFunction<String, Tuple2<Long,String>>() {
            Random random = new Random();
            @Override
            public void flatMap(String value, Collector<Tuple2<Long, String>> out) throws Exception {
                Integer i = random.nextInt(10);
                out.collect(Tuple2.of(i.longValue(),value));
            }
        }).keyBy(new KeySelector<Tuple2<Long, String>, Long>() {
            @Override
            public Long getKey(Tuple2<Long, String> value) throws Exception {
                return value.f0;
            }
        }).connect(broadcast)
                .process(new KeyedBroadcastProcessFunction<Long, Tuple2<Long, String>, Rule, String>() {

                    private final MapStateDescriptor<String, Rule> ruleStateDescriptor =
                            new MapStateDescriptor<>(
                                    "RulesBroadcastState",
                                    BasicTypeInfo.STRING_TYPE_INFO,
                                    TypeInformation.of(new TypeHint<Rule>() {}));

                    @Override
                    public void processElement(Tuple2<Long, String> value, ReadOnlyContext ctx, Collector<String> out) throws Exception {
                        for(Map.Entry<String, Rule> entry : ctx.getBroadcastState(ruleStateDescriptor).immutableEntries()) {
                            String keyWord = entry.getKey();
                            if(value.f1.contains(keyWord)) {
                                value.f1  = value.f1.replaceAll(keyWord,entry.getValue().replaceWord);
                            }
                        }
                        out.collect(value.f1);
                    }

                    @Override
                    public void processBroadcastElement(Rule value, Context ctx, Collector<String> out) throws Exception {
                        ctx.getBroadcastState(ruleStateDescriptor).put(value.keyword,value);
                    }
                })
                .print();

        env.execute();

    }
}
